package com.lori.netshop.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lori.netshop.pojo.CarItem;
import com.lori.netshop.pojo.Order;
import com.lori.netshop.pojo.TbUser;
import com.lori.netshop.service.CarService;
import com.lori.netshop.service.OrderService;
import com.lori.netshop.util.NetshopResult;

@Controller
@RequestMapping("/order")
public class OrderController {
	@Autowired
	private CarService carServiceimp;
	@Autowired
	private OrderService orderServiceimp;
	
	@Value("${BASE_SSO}")
	private String BASE_SSO;
	@Value("${SSO_LOGIN}")
	private String SSO_LOGIN;
	/**
	 * 跳转到页面结算
	 * 
	 */
	@RequestMapping("/order-cart")
	public String showCarSum(HttpServletRequest request,HttpServletResponse response,Model model){
		List<CarItem> carItems = carServiceimp.findCarItems(request, response);
		model.addAttribute("cartList", carItems);
		return "order-car";
	}
	/**
	 * 创建订单
	 */
	@RequestMapping("/create")
	public String createOrder(Order order,HttpServletRequest request,Model model,HttpServletResponse response){
		NetshopResult result = orderServiceimp.createOrder(order, request);
		if(result.getStatus() == 500){
			try {
				response.sendRedirect(BASE_SSO+SSO_LOGIN+"?redirectUrl="+request.getRequestURL());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				model.addAttribute("message", "订单创建失败，请稍后再试-");
				return "error/exception";
			}
		}else if(result.getStatus() == 200){
			model.addAttribute("orderId", result.getData().toString());
			model.addAttribute("payment", order.getPayment());
			model.addAttribute("date", new DateTime().plusDays(3).toString("yyyy-MM-dd"));
			return "success";	
		}else{
			model.addAttribute("message", "订单创建失败，请稍后再试+");
			return "error/exception";
		}
		model.addAttribute("message", "订单创建失败，请稍后再试=");
		return "error/exception";
	}
	/**
	 * 展示我的订单
	 */
	@RequestMapping("/orderList")
	public String showOrderList(HttpServletRequest request,Model model){
		//获取数据
		TbUser user = (TbUser) request.getAttribute("user");
		List<Order> orders = orderServiceimp.getOrders(user.getId());
		System.out.println(user.getId()+"---------------");
		model.addAttribute("orders", orders);
		return "my-orders";
	}
}
